home *** CD-ROM | disk | FTP | other *** search
- Path: noc.netcom.net!news
- From: Tarang Deshpande <tarang@willows.com>
- Newsgroups: comp.lang.c
- Subject: Re: switching base 10 to hex
- Date: Thu, 04 Apr 1996 17:47:36 -0800
- Organization: NETCOM Network Operations
- Message-ID: <31647BB8.759C@willows.com>
- References: <4ju6a9$kl6@coranto.ucs.mun.ca>
- NNTP-Posting-Host: daffy.willows.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0GoldB2 (Win95; I)
-
- J.Deeley wrote:
- >
- > Hello,
- >
- > I read the faq (very interesting!) and also did a search at the Internet
- > Public Library (at which I found some other realy neat info) but I am
- > still stuck on this. Appologies if this is the wrong group to ask.
- > Perhaps you could point me to the right group, or a web site with this
- > info. I need?
- >
- > I am teaching myself to program in C using a book that came with my
- > compiler. In the book I just ran into a small section which deals with
- > switching base 10 numbers to base two numbers (no problems there, thats
- > easy) and also switching base 10 numbers to hexidecimal (base 16).
- >
- > Agh! My book does a lousy job of explaining how that works, and one of
- > the alternative explanations I found on the net does no better. Can
- > someone give me a good, simple way to get a hexadecimal number from a
- > normal number? Like the number 400 for instance? Go slow...
- >
- > JD
- >
- > --
- > Caution...Newbie Programmer on Board!
- > --
-
-
- I am assuming that you want to know the math behind hex numbers and not
- just how to print them out from a C program. If so read on, otherwise
- sorry.
-
- First off understand what a number like 400 means in decimal. It actually
- means ( 4 * 100 ) + ( 0 * 10 ) + ( 0 * 1 ) or better yet ( 4 * 10^2 ) +
- ( 0 * 10^1 ) + ( 0 * 10^0 ). In hexidecimal a number is represented in
- exactly the same way except that instead of 10s you use 16s. So the number
- 0x400 ( 400 hex which is not equal 400 decimal ) would be ( 4 * 16^2 ) +
- ( 0 * 16^1 ) + ( 0 * 16^0 ).
-
- Got that so far?
-
- Now the question becomes how do you convert a decimal number to hex. Using
- 400 decimal we want to find the following
-
- 400 = ( h1 * 16^n ) + ( h2 * 16^(n-1) ) + ( h3 * 16^(n-2) ) + ... ( hn+1 * 16^0 )
-
- note that if n were large ( in this case greater than 2 ) then h1 would be 0 just as
- 400 = ( 0 * 10^3 ) + ...
-
- So in converting the following algorithm will yield the proper result.
-
- find n such that 16^n >= 400 or whatever other number your trying to convert.
- In this case n = 3 because 16^3 = 4096 and 4096 > 400.
-
- Now how many times does 16^(n-1) = 16^(2) = 256 go into 400, the answer is 1.
- What's left over? The answer is 144.
- Now how many times does 16^(n-2) = 16^1 = 16 go into 144, the answer is 9.
- What's left over? The answer is 0.
-
- Therefore 400 = ( 1 * 16^2 ) + ( 9 * 16^1 ) + ( 0 * 16^0 ) or 0x190
-
- Got it?
-